/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package imp.reciever.output;

import dom.Command;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 *
 * @author julian.pena
 */
public class SaveFiles extends OutputReciever{

    private File directory;
    
    public SaveFiles(File directory) throws Exception {
        super(null);
        if (!directory.isDirectory()) {
            throw new Exception("In not a folder");
        }
        this.directory = directory;
    }
    
    public SaveFiles(String path) throws Exception {
        super(null);
        File directory = new File(path);
        if (!directory.isDirectory()) {
            throw new Exception("In not a folder");
        }
        this.directory = directory;
    }
    

    public SaveFiles(File folder, Command command) {
        super(null, command);
    }
    
    @Override
    public void action() throws Exception {
        while (fileName.equals("")) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException interruptedException) {}
        }
        stop = false;
        String absolutePath = directory.getAbsolutePath();
        byte[] buf = new byte[BUFFER_SIZE];
        while (true) {
            if (fileName == null) {
//                inputStream.close();
                System.out.println("termino de guardar en: " + directory.getAbsolutePath());
                return;
            }
            String[] ss = fileName.split(SEPARATOR);
            fileName = ss[ss.length -1];
            File file = new File(absolutePath + SEPARATOR + fileName);
            System.out.println("Guardando: " + file.getAbsolutePath());
            outputStream =  new FileOutputStream(file);
            int len;
            while ((len = inputStream.available()) > -1) {
                if (len<= 0) {
                    if (stop) {
                        break;
                    }
                }
                len = inputStream.read(buf);
                outputStream.write(buf, 0, len);
            }
            stop = false;
            outputStream.close();
        }
        
    }

    @Override
    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public boolean isInputReady() {
        if (inputStream != null) {
            return true;
        } else {
            return false;
        }
    }
}
